import mqtt from 'mqtt'

// MQTT 配置
const options = {
  clean: true,
  connectTimeout: 4000,
  clientId: 'vue3-client-' + Math.random().toString(16).substr(2, 8),
}

// MQTT 代理地址（示例使用公共测试服务器）
const brokerUrl = 'ws://192.168.110.88:8083/mqtt'

class MQTTClient {
  constructor() {
    this.client = null
  }

  connect() {
    console.log('Connecting to MQTT broker:', brokerUrl)
    this.client = mqtt.connect(brokerUrl, options)

    // 连接成功
    this.client.on('connect', () => {
      console.log('MQTT Connected')
      // 可以在这里订阅一些默认主题
      this.subscribe('test/topic')
    })

    // 错误处理
    this.client.on('error', (error) => {
      console.error('MQTT Error:', error)
    })

    // 接收消息
    this.client.on('message', (topic, message) => {
      console.log(`Received message from topic ${topic}:`, message.toString())
    })
  }

  subscribe(topic, qos = 0) {
    this.client.subscribe(topic, { qos }, (err) => {
      if (!err) {
        console.log(`Subscribed to ${topic}`)
      }
    })
  }

  publish(topic, message, qos = 0) {
    this.client.publish(topic, message, { qos })
  }

  disconnect() {
    if (this.client) {
      this.client.end()
    }
  }
}

export const mqttClient = new MQTTClient()
